package main

import (
	"fmt"
	"image"
	"image/jpeg"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"sync"

	"github.com/nfnt/resize"
)

func main() {
	// 指定图片所在的文件夹
	inputFolder := "./images" // 替换为你的图片文件夹路径

	// 获取文件夹下的所有文件
	files, err := ioutil.ReadDir(inputFolder)
	if err != nil {
		fmt.Println("Error reading directory:", err)
		return
	}

	// 使用 WaitGroup 等待所有 goroutine 完成
	var wg sync.WaitGroup
	wg.Add(len(files))

	for _, file := range files {
		if !file.IsDir() {
			// 启动 goroutine 处理每张图片
			go func(filename string) {
				defer wg.Done()

				processImage(filepath.Join(inputFolder, filename))
			}(file.Name())
		}
	}

	// 等待所有 goroutine 完成
	wg.Wait()

	fmt.Println("All images processed successfully.")
}

// 处理单张图片的函数
func processImage(inputFilename string) {
	// 打开图片文件
	file, err := os.Open(inputFilename)
	if err != nil {
		fmt.Printf("Error opening file %s: %v\n", inputFilename, err)
		return
	}
	defer file.Close()

	// 解码图片
	img, _, err := image.Decode(file)
	if err != nil {
		fmt.Printf("Error decoding image %s: %v\n", inputFilename, err)
		return
	}

	// 获取图片的尺寸
	bounds := img.Bounds()
	width := bounds.Dx()
	height := bounds.Dy()

	// 裁剪掉最底部 200px
	croppedImg := img.(interface {
		SubImage(r image.Rectangle) image.Image
	}).SubImage(image.Rect(0, 0, width, height-200))

	// 保存裁剪后的原图
	outputFilename := generateOutputFilename(inputFilename, "_cropped")
	err = saveImageAsJPEG(outputFilename, croppedImg)
	if err != nil {
		fmt.Printf("Error saving cropped image %s: %v\n", outputFilename, err)
		return
	}

	// 创建缩略图（缩略图大小为原图的六分之一）
	thumbnailWidth := width / 6
	thumbnailHeight := height / 6
	thumbnail := resize.Resize(uint(thumbnailWidth), uint(thumbnailHeight), croppedImg, resize.Lanczos3)

	// 保存缩略图
	thumbnailFilename := generateOutputFilename(inputFilename, "_thumbnail")
	err = saveImageAsJPEG(thumbnailFilename, thumbnail)
	if err != nil {
		fmt.Printf("Error saving thumbnail %s: %v\n", thumbnailFilename, err)
		return
	}

	fmt.Printf("Processed image %s\n", inputFilename)
}

// 生成输出文件名，添加后缀用于区分处理过的图片
func generateOutputFilename(inputFilename, suffix string) string {
	ext := filepath.Ext(inputFilename)
	filename := strings.TrimSuffix(inputFilename, ext)
	return filename + suffix + ext
}

// 将图片保存为 JPEG 格式
func saveImageAsJPEG(filename string, img image.Image) error {
	outFile, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer outFile.Close()

	options := &jpeg.Options{Quality: 90}
	err = jpeg.Encode(outFile, img, options)
	if err != nil {
		return err
	}

	return nil
}
